package com.wobito.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wobito.mapper.UserMapper;
import com.wobito.pojo.bean.User;
import com.wobito.pojo.dto.user.LoginInfoDTO;
import com.wobito.pojo.enums.UserRoleEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Wangbaba
 */
@Service
public class UserDatailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        boolean isEnabled = true;
        boolean accountNonLocked = true;
        //查询登录用户
        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username);
        User user = userMapper.selectOne(userQuery);
        if(ObjectUtil.isEmpty(user)){
            isEnabled = false;
        }
        if (user.getRoleId().equals(UserRoleEnum.REGION_ADMIN.getCode())){
            accountNonLocked = false;
        }
        LoginInfoDTO loginInfoDto = new LoginInfoDTO();
        BeanUtils.copyProperties(user,loginInfoDto);

        List<GrantedAuthority>  authorities=new ArrayList<>();
        if (user.getRoleId().equals(UserRoleEnum.SYSTEM_ADMIN.getCode())){
            authorities.add(new SimpleGrantedAuthority("ROLE_SUPER_ADMIN"));
        }else if (user.getRoleId().equals(UserRoleEnum.NORMAL_ADMIN.getCode())){
            authorities.add(new SimpleGrantedAuthority("ROLE_NOMAL_ADMIN"));
        }else if (user.getRoleId().equals(UserRoleEnum.REGION_ADMIN.getCode())){
            authorities.add(new SimpleGrantedAuthority("ROLE_REGION_ADMIN"));
        }

        String loginInfo = JSONUtil.toJsonStr(loginInfoDto);
        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(loginInfo, user.getPassword(), isEnabled, true, true, accountNonLocked, authorities);
        return user1;
    }


}
